package com.example.isbnbook;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("book")
public class BookController {
    @GetMapping("add")
    public String add(){
        return "add";
    }

    @GetMapping("delete")
    public String delete (){
        return "delete";
    }

    @GetMapping("edit")
    public String edit(){
        return "edit";
    }

    @GetMapping("search")
    public String search(){
        return "search";
    }
    @GetMapping("isbn/{isbn}")
    public Book isbn(@PathVariable String isbn ,@RequestParam(required = true) String apikey) throws IOException {
        Book book =null;
        String url = "http://120.24.69.59:8083/book/isbn/"+ isbn +"?apikey=sb.250.s.j.b";
        System.out.println(url);
        String userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 SLBrowser/9.0.5.8121 SLBChan/111 SLBVPV/64-bi";
        Document document = Jsoup.connect(url)
                .userAgent(userAgent)
                .ignoreContentType(true)
                .get();
        String result = document.body().text();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode originBookInfo = mapper.readTree(result);
        if (originBookInfo != null && originBookInfo.has("ret") && originBookInfo.get("ret").asInt() == 0) {
            JsonNode data = originBookInfo.get("data");

            String title = data.path("name").asText(null);
            String author = data.path("author").asText(null);
            String publisher = data.path("publishing").asText(null);
            String published = data.path("published").asText(null);
            String description = data.path("description").asText(null);
            String coverImage = data.path("photoUrl").asText(null);
            String price = data.path("price") != null ? data.path("price").asText().replace("元", "") : null;
            String doubanScore = data.path("doubanScore").asText(null);
            String page = data.path("pages").asText(null);
            String authorIntro = data.path("authorIntro").asText(null);

            book = new Book();
            book.setIsbn(isbn);
            book.setTitle(title);
            book.setAuthor(author);
            book.setAuthorIntro(authorIntro);
            book.setPublisher(publisher);
            book.setPublishDate(published);
            book.setDescription(description);
            book.setCoverImage(coverImage);
            book.setPrice(price);
            book.setDoubanScore(doubanScore);
            book.setPage(page);

        }

        return book;
    }
}

